<?php

namespace App\Exceptions;

use App\Common\Func;
use App\Common\statement\ResponseStatement;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Throwable;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param \Throwable $exception
     * @return void
     *
     * @throws \Throwable
     */
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Throwable $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $exception)
    {
        $message = 'Network error, please try again later';
        if (env('APP_DEBUG')) {
            $err = [
                'file' => $exception->getFile(),
                'line' => $exception->getLine()
            ];
            $message = $exception->getMessage();
        }

        if (strpos($exception->getMessage(), 'timed out after') !== false) {
            $message = 'Network timeout, please try again later~';
        }
        if (strpos($exception->getMessage(), 'Too Many Attempts') !== false) {
            $message = 'Too many attempts, please try again later~';
        }
        // Method not allowed
        if ($exception instanceof MethodNotAllowedHttpException) {
            return $this->exceptionResponse(501);
        }
        // Route not found
        if ($exception instanceof RouteNotFoundException || $exception instanceof NotFoundHttpException) {
            return $this->exceptionResponse(404, 'Route not found');
        }
        // Token expired
        if ($exception instanceof TokenExpiredException) {
            return $this->exceptionResponse(401, 'Log in expired, please log in again');
        }
        if ($exception instanceof UnauthorizedHttpException) {
            return $this->exceptionResponse(401, 'Unauthorized access');
        }

        $err = $err ?? null;
        if ($exception instanceof ApiException) {
            $message = $exception->getMessage();
        }
        return $this->exceptionResponse($exception->getCode(), $message, $err);
//        return parent::render($request, $exception);
    }

    private function exceptionResponse($code, $message = '', $err = null)
    {
        $code = $code == 0 ? 1 : $code;
        $response = Func::response($code, $message, $err);
        return response($response)->header('Content-Type', 'application/json');
    }
}
